﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AvaMaid.Messages;
using CommunityToolkit;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Messaging;
using FanaticGene.AvaloniaMaid.Core;

namespace AvaMaid.ViewModels
{
    public class ControlThemeViewModel : ObservableObject, IRecipient<SearchTextChangedEventArgs>
    {
        ///<summary>文件列表。</summary>
        public ObservableCollection<CodeUri> Files { get; } = new ObservableCollection<CodeUri>();

        ///<summary>代码</summary>
        public string Code { get => _code; set { SetProperty(ref _code, value); } }
        private string _code;

        public ControlThemeViewModel()
        {
            WeakReferenceMessenger.Default.Register(this);
            DisplayAll();
        }

        private void DisplayAll()
        {

            var archive = Globals.Archive;
            var resourceFiles = archive.Value.ControlThemes.ResourceFiles;
            var files = resourceFiles;
            Files.Clear();
            if (files != null)
            {
                foreach (var file in files)
                {
                    Files.Add(file);
                }
            }
        }

        public void Receive(SearchTextChangedEventArgs message)
        {
            App.Current.Dispatcher.Invoke(() =>
            {
                var files = GetFiles(message.Text);
                Files.Clear();
                if (files != null)
                {
                    foreach (var file in files)
                    {
                        Files.Add(file);
                    }
                }

            });

        }

        public IEnumerable<CodeUri> GetFiles(string pattern)
        {
            var archive = Globals.Archive;
            var resourceFiles = archive.Value.ControlThemes.ResourceFiles;
            if (string.IsNullOrWhiteSpace(pattern)) { DisplayAll(); return resourceFiles; }
            if (pattern.Length <= 2) { return null; }
            var files = resourceFiles.Where(f => Conatin(f.Name, pattern)).OrderBy((f) => Ratio(pattern, f.Name)).Take(20).OrderBy(f=>f.Name.Length);
            return files.ToArray();
        }

        private int Ratio(string name, string pattern)
        {
            return FuzzySharp.Fuzz.Ratio(pattern, name);
        }

        ///<summary>包含。</summary>
        private bool Conatin(string name, string pattern)
        {
            if (string.IsNullOrWhiteSpace(name)) return false;
            if (string.IsNullOrWhiteSpace(pattern)) return false;
            return name.IndexOf(pattern, comparisonType: StringComparison.OrdinalIgnoreCase) >= 0;
        }
    }
}
